//
//  WtrackerAppDelegate.m
//  Wtracker
//
//  Created by Anna on 6/25/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "WtrackerAppDelegate.h"
#import "SetupViewController.h"
#import "EntryViewController.h"

#define UOMTITLE @"Unit of Measure"

/*static sqlite3 *database = nil;
static sqlite3_stmt *deleteStmt = nil;
static sqlite3_stmt *addStmt = nil;
*/
@implementation WtrackerAppDelegate

@synthesize window, nav, myDict, tmpDate, databaseName, databasePath, weights, unitArray;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

	// on first setup show setup view, otherwise load default (entry) view
	NSLog(@" in app did start");
	[self loadMySettings];
	[window addSubview:[nav view]];	

	databaseName = @"Wtracker.sql";
	
	// Get the path to the documents directory and append the databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
	
	unitArray = [[NSArray alloc] initWithObjects:@"lbs", @"kgs",nil];
	
	[self checkAndCreateDatabase];
	[self readWeightsFromDatabase];
	
	[window makeKeyAndVisible];
	return YES;
}

-(void)saveSettings{
	
	NSArray *dirPaths;
	NSString *docsDir;
	
	dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
												   NSUserDomainMask, YES);
	
	docsDir = [dirPaths objectAtIndex:0];
	NSString *myPath = [docsDir stringByAppendingFormat:@"/wTrackerSettings.xml"];
	NSLog(@"myPath: %@", myPath);
	
	NSFileManager *filemgr;
	NSDictionary *attribs;

	filemgr = [NSFileManager defaultManager];
	attribs = [filemgr attributesOfItemAtPath:docsDir error: NULL];

	NSLog (@"File type %@", [attribs objectForKey: NSFileType]);
	NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions])	;
	BOOL response = [myDict writeToFile:myPath atomically:YES];
	if(response){
		NSLog(@"Success- no error saving file to system");
	} else {
		NSLog(@"Error saving file to system");
	}
}

-(void)loadMySettings{
	// reload from xml to make sure up to date
	if(self.myDict){
		self.myDict = nil;
	}
	NSArray *dirPaths;
	NSString *docsDir;
	
	dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
												   NSUserDomainMask, YES);
	
	docsDir = [dirPaths objectAtIndex:0];
	NSString *myPath = [docsDir stringByAppendingFormat:@"/wTrackerSettings.xml"];
	myDict = [[NSMutableDictionary alloc] initWithContentsOfFile:myPath];
	if([myDict count] == 0){
		// first time launching
		NSString *myPath = [[NSBundle mainBundle] pathForResource:@"wTrackerSettings" ofType:@"xml"];           
		myDict = [[NSMutableDictionary alloc] initWithContentsOfFile:myPath];
	}

}	

-(BOOL)logWeight:(float)aWeight logDate:(NSString *)aLogDate{
	
	// determine which UOM is preferred, then calculate and pass to add Weight method
	int weightID;

	NSString *thisLogDate = [aLogDate retain];
	NSString *theUOMStr = [myDict objectForKey:UOMTITLE]; // technically hsould pass from entry page
	NSNumber *idx = [NSNumber numberWithInt:[unitArray indexOfObject:theUOMStr]];
	float weight_kgs;
	float weight_lbs;
	
	if([idx intValue] > 1) {
		// was logged in kgs
		weight_kgs = aWeight;
		weight_lbs = aWeight * 2.2;
	} else {
		// was loged in lbs
		weight_lbs = aWeight;
		weight_kgs = aWeight / 2.2;
	}
	NSNumber *nWKgs = [[NSNumber numberWithFloat:weight_kgs] retain];
	NSNumber *nWLbs = [[NSNumber numberWithFloat:weight_lbs] retain];
	NSLog(@"in appdel: the logdate: %@, and the weight: %f, in kgs: %f, and lbs: %f",thisLogDate, aWeight, weight_kgs, weight_lbs);

	sqlite3_stmt *addStmt = nil;
	sqlite3 *database;
	if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
		NSAssert1(0, @"Error while creating db. '%s'", sqlite3_errmsg(database));
	}

	const char *sql = "insert into weights (weight_lbs, weight_kgs, logdate) Values (?, ?, ?)";
	if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
		NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));

	
	NSLog(@"got past the statement stuff, now to binding, logdate: %@", aLogDate);

	sqlite3_bind_double(addStmt, 1, [nWLbs doubleValue]);
	sqlite3_bind_double(addStmt, 2, [nWKgs doubleValue]);
	sqlite3_bind_text(addStmt, 3, [thisLogDate UTF8String], -1, SQLITE_TRANSIENT);
	
	NSLog(@"past the bindings");
	
	if(SQLITE_DONE != sqlite3_step(addStmt)){
		NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
	}

	weightID = sqlite3_last_insert_rowid(database);
	
	/*[weights addObject:[[NSArray alloc] initWithObjects:
						[NSNumber numberWithInt:weightID], 
						[NSNumber numberWithFloat:weight_lbs], 
						[NSNumber numberWithFloat:weight_kgs], aLogDate, nil]];

	*/ 
	[self readWeightsFromDatabase];

	sqlite3_reset(addStmt);
	
	NSLog(@"%d the weightID", weightID);
	return YES;
}



#pragma mark tableview db methods

-(BOOL) removeFromList:(NSInteger)index { 
	
	NSNumber *wID = [NSNumber numberWithInt:[[[weights objectAtIndex:index] objectAtIndex:0] intValue] ];

	sqlite3_stmt *delStmt;
	sqlite3 *database;

	if (sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
		NSAssert1(0, @"Error while creating db. '%s'", sqlite3_errmsg(database));
		return NO;
	}	 
	 const char *sql = "delete from weights where id = ?";
	 if(sqlite3_prepare_v2(database, sql, -1, &delStmt, NULL) != SQLITE_OK){
		 NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
		 return NO;
	 }
	 
	 sqlite3_bind_int(delStmt, 1, [wID intValue]);
	 
	 if(SQLITE_DONE != sqlite3_step(delStmt)){
		 NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
	 } 
	 //Reset the add statement.
	 sqlite3_reset(delStmt);
	 
	[weights removeObjectAtIndex:index];
	return YES;
	
}

-(void) moveFromOriginal:(NSInteger)indexOriginal toNew:(NSInteger)indexNew {
	
	NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:weights];
	
	id tempObject = [tempArray objectAtIndex:indexOriginal];
	
	[tempArray removeObjectAtIndex:indexOriginal];
	
	[tempArray insertObject:tempObject atIndex:indexNew];
	
	weights = tempArray;
	
}



-(void)readWeightsFromDatabase {
	// Setup the database object
	sqlite3 *database;
	
	weights = [[[NSMutableArray alloc] init] retain];	
	
	if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		// Setup the SQL Statement and compile it for faster access
		const char *sqlStatement = "select * from weights order by logdate desc";
		sqlite3_stmt *compiledStatement;
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				// Read the data from the result row
				NSNumber *theId = [NSNumber numberWithInt:sqlite3_column_int(compiledStatement,0)];
				NSNumber *weight_lbs = [NSNumber numberWithFloat:sqlite3_column_double(compiledStatement,1)];
				NSNumber *weight_kgs = [NSNumber numberWithFloat:sqlite3_column_double(compiledStatement,2)];
				NSString *log_date = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
				
				NSArray *tmpArray = [[NSArray alloc] initWithObjects:theId, weight_lbs, weight_kgs, log_date, nil];
				[weights addObject:tmpArray];
				
			}
		}
		// Release the compiled statement from memory
		sqlite3_finalize(compiledStatement);
		
	}
	sqlite3_close(database);
	
	
}

-(void) checkAndCreateDatabase{
	BOOL success;
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	success = [fileManager fileExistsAtPath:databasePath];
	
	if(success) return;
	
	
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
	
	[fileManager release];
}

+ (void) finalizeStatements {
/*	
	if(database) sqlite3_close(database);
	if(deleteStmt) sqlite3_finalize(deleteStmt);
	if(addStmt) sqlite3_finalize(addStmt);*/
}



- (void)dealloc {
    [window release];
	[tmpDate release];
	[nav release];
    [super dealloc];
}


@end
